import time
import multiprocessing as mp
import cv2



def image_put(q, file_path):
    cap = cv2.VideoCapture(file_path)
    if cap.isOpened():
        print('opened')

    while True:
        q.put(cap.read()[1])
        q.get() if q.qsize() > 1 else time.sleep(0.01)

def image_get(q, window_name):
    # cv2.namedWindow(window_name, flags=cv2.WINDOW_FREERATIO)
    while True:
        frame = q.get()
        print("1")
        cv2.imshow(window_name, frame)
        cv2.waitKey(1)




def run_single_camera():
    # user_name, user_pwd, camera_ip = "admin", "admin123456", "172.20.114.196"
    user_name, user_pwd, camera_ip = "admin", "buaa0707", "192.168.1.103"
    file = "data/suidao.mp4"
    fname = "suidao"
    # user, pwd, ip, channel = "admin", "buaa0707", "192.168.1.103", 1  # 主码流
    user, pwd, ip, channel = "admin", "buaa0707", "192.168.1.103", 2  # 子码流 分辨率低
    file_path = "rtsp://%s:%s@%s//Streaming/Channels/%d" % (user, pwd, ip, channel)  # HIKIVISION new version 2017


    mp.set_start_method(method='spawn')  # init
    queue = mp.Queue(maxsize=2)
    processes = [mp.Process(target=image_put, args=(queue, file_path)),
                 mp.Process(target=image_get, args=(queue, camera_ip))]

    [process.start() for process in processes]
    [process.join() for process in processes]







def run():
    # run_opencv_camera()  # slow, with only 1 thread
    run_single_camera()  # quick, with 2 threads

    pass


if __name__ == '__main__':
    run()
